package tcp;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/*
* 客户端发送文件给服务器,服务端将文件保存到本地.
* */
public class TcpTest2 {
    @Test
    public void client() throws IOException {

        //1:socket
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9999);
        //2:输出流
        OutputStream os = socket.getOutputStream();

        //3:文件流
        FileInputStream fis = new FileInputStream(new File("image.jpeg"));
        //4:写入文件(输出文件)
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }

        //5:资源关闭
        fis.close();
        os.close();
        socket.close();

    }

    @Test
    public void server(){
        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            ss = new ServerSocket(9999);

            socket = ss.accept();

            is = socket.getInputStream();

            fos = new FileOutputStream(new File("image2.jpeg"));

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
